package process

/*400 业务处理*/

import (
	"dmsv/agent"
	"dmsv/common"
	"dmsv/queue"
	"dmsv/session"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/task"
)

const (
	task_run_every_zero_oclock = "0 0 0 * * *"
)

func callInHanldeCreate(appId, number, media, acd string, getKey bool) *Company {

	//收到新的号码监听消息，创建监听任务
	handle := &Company{
		appId:          appId,
		navigateAudio:  media,
		number:         number,
		callEventChan:  make(chan *session.CallBackData, 100),
		queEventChan:   make(chan *queue.Event, 100),
		service:        make(map[string]*agent.AgentInfo),
		acd:            acd,
		getKey:         getKey,
		callInTransfer: make(map[string]TransferInfo),
	}

	//满意度默认语音
	handle.satisfaction.EndVoice = voice_satisfaction_goodbye
	handle.satisfaction.TipVoice = voice_satisfaction

	//等待语音
	handle.waitVoice.waitVoice = voice_wait_answer
	handle.waitVoice.stopSecond = voice_wait_delay_init

	//添加到监听号码列表
	go handle.callInProcess()

	gEterpriceHandle[appId] = handle

	//定时任务 重置坐席
	taskName := fmt.Sprintf("serviceReset_%v", handle.appId)
	t := task.NewTask(taskName, task_run_every_zero_oclock, handle.serviceReset)

	handle.resetTask = taskName
	task.AddTask(taskName, t)

	return handle
}

//从数据库中加载呼入号码、坐席、队列情况
func callInInit() {

	gEterpriceHandle = make(map[string]*Company)

}

func AddNewEnterprice(appId, media, number, acd string, getKey bool) (*Company, error) {

	handle, ok := gEterpriceHandle[appId]
	if !ok {
		logs.Debug("create company handle:%v for number:%v", appId, number)
		handle = callInHanldeCreate(appId, number, media, acd, getKey)
		gEterpriceHandle[appId] = handle
	} else {
		handle.number = number
		handle.navigateAudio = media
		handle.getKey = getKey

	}

	err := error(nil)
	if number != "" {
		err = session.AddCallInNumber(number, handle.callEventChan)
	}

	return handle, err
}

func EnterpriceUpdate(appId, media, acd, number string) error {

	handle, ok := gEterpriceHandle[appId]
	if ok {

		if media != "" {
			handle.navigateAudio = media
		}

		if acd != "" {
			handle.acd = acd

			logs.Debug("update all queue distrib to %v for company %v", acd, appId)

			queue.UpdateQueCompanyDistrib(appId, acd)
		}

		if number != "" {

			session.DelListenNumber(handle.number)
			handle.number = number
		}

	} else {
		logs.Error("cannot find enterprise:%v", appId)
		return fmt.Errorf("appIdErr")
	}
	return nil
}

func GetDisplay(appId string) (string, error) {

	handle, ok := gEterpriceHandle[appId]
	if ok {

		if len(handle.display) == 0 {
			return "", fmt.Errorf("Empty")
		}

		res := displayInfo{
			count: 99999999,
		}

		for _, display := range handle.display {
			if res.count > display.count {
				res = display
			}
			logs.Debug("获取最小外呼外显号:%v 外呼次数:%v ", res.display, res.count)
			return res.display, nil
		}
	}

	logs.Error("cannot find enterprise:%v", appId)
	return "", fmt.Errorf("appIdNotExist")
}

func EnterpriceAddNumber(appId, number string, display bool) error {

	handle, ok := gEterpriceHandle[appId]
	if ok {
		if display {
			return handle.AddDisplay(number)
		} else {
			return handle.ListenNumber(number)
		}

	} else {
		logs.Error("cannot find enterprise:%v", appId)
	}

	return fmt.Errorf("company:%v is not exist", appId)
}

func EnterpriceDelNumber(appId, number string, display bool) error {

	handle, ok := gEterpriceHandle[appId]
	if ok {
		if display {
			handle.DelDisplay(number)
		} else {
			handle.DelListenNumber(number)
		}

		return nil
	} else {
		logs.Error("cannot find enterprise:%v", appId)
	}

	return fmt.Errorf("company:%v is not exist", appId)
}

func EnterpriceConfigCallIn(appId, number, transferType, info string) error {

	handle, ok := gEterpriceHandle[appId]
	if ok {

		handle.SetTransfer(number, transferType, info)
		return nil
	} else {
		logs.Error("cannot find enterprise:%v", appId)
	}

	return fmt.Errorf("company:%v is not exist", appId)
}

func AddNewQue(appId, name, key, media, distrb string, queId int) bool {

	handle, ok := gEterpriceHandle[appId]
	if !ok {
		logs.Error("no company info:%v", appId)
		return false
	}

	queue.CreateNewQue(appId, name, key, media, handle.Distribution(), distrb, queId, handle.queEventChan)

	return true
}

func UpdateQue(appId, name, key, media, distrb string, queId int) bool {

	err := queue.UpdateQue(appId, name, key, media, distrb, queId)
	if err != nil {
		logs.Error("[%v][%v] update failed:%v", appId, name, err)
		return false
	}
	return true
}

func DelQue(appId, name string) bool {

	queue.DelQue(appId, name)

	return true
}

func SatisfactionConfig(appId, active, autoSend, tipVoice, endVoice string) error {
	handle, ok := gEterpriceHandle[appId]
	if ok {
		handle.SatisfactionConfig(active, autoSend, tipVoice, endVoice)

		return nil
	} else {
		return fmt.Errorf("company:%v is not exist", appId)
	}
}

func SatisfactionDo(appId, callId string) error {

	ss, ok := session.GetSession(callId)
	if !ok {
		return fmt.Errorf("Call %v Invalid", callId)
	}

	handle, ok := gEterpriceHandle[appId]
	if ok {

		if false == handle.satisfaction.Active {
			logs.Debug("[%v] 满意度未开启,忽略指令", callId)
			return nil
		}

		media := common.MediaFullPath(appId, handle.satisfactionPlayFile())
		ss.Satisfaction(media)

		return nil

	} else {
		return fmt.Errorf("company:%v is not exist", appId)
	}
}
